<template>
  <upload-excel :on-success="onSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { reqImportEmployeeAPI } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    async onSuccess (data) {
      if (data.results.length === 0) return
      const arr = this.translateData(data.results)
      try {
        const ret = await reqImportEmployeeAPI(arr)
        if (ret.code !== 10000) return this.$message.success('有重复导入')
        this.$message.success(ret.message)
        this.$router.push('/employees')
      } catch (err) {
        console.log(err)
        this.$message.error('网络错误')
      }
    },
    beforeUpload (data) {
      if (data.size > 10100) return false
      return true
    },
    // 转换格式数据
    translateData (results) {
      // 中文和属性的映射关系
      const userRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const row = {}
        for (const key in userRelations) {
          const name = userRelations[key]
          const value = item[key]
          if (['timeOfEntry', 'correctionTime'].includes(name)) {
            // 这个属性是时间，需要把数字转换为年月日格式
            row[name] = this.formatDate(value)
          } else {
            // 非日期格式不做处理
            row[name] = value
          }
        }
        arr.push(row)
      })
      console.log(arr)
      return arr
    },
    // 处理时间+

    formatDate (numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }

}

</script>

<style>
</style>
